<template>
  <Top-Page class="collect-box">
    <NavBar title="收藏" leftText="返回" left-arrow @click-left="onClickLeft"></NavBar>
    <view class="list" v-if="!empty">
      <view class="list-unit" v-for="(item, index) in list">
        <image class="avatar-img" v-if="item.fromUser" :src="item.fromUser.avatar" mode="scaleToFill"></image>
        <image class="avatar-img" v-else :src="user.avatar" mode="scaleToFill"></image>

        <view class="message-wrap">
          <view class="msg-name" v-if="item.fromUser">{{ item.fromUser.realname }}</view>

          <view class="msg-content">
            <!-- 文字消息 -->
            <template v-if="item.type == 'text'">
              {{ item.content }}
            </template>

            <!-- 图片消息 -->
            <image v-else-if="item.type == 'image'" :src="item.content" />

            <!-- 语音消息 -->
            <view
              v-else-if="item.type == 'voice'"
              :data-voice="item.content"
              @tap="playVoice"
              :style="{ width: item.extends.duration * 3 + 'px' }"
            >
              <text
                class="f-16 cuIcon-subscription rotate45"
                :class="[index == playIndex ? 'c-white' : '', item.fromUser.id == user.user_id ? 'rotate225' : '']"
              ></text>
              <text class="im-voice-msg-text" :class="[index == playIndex ? 'c-white' : '']">
                {{ item.extends.duration }} "
              </text>
            </view>

            <!-- 文件消息 -->
            <view v-else-if="item.type == 'file'">
              <view
                class="file-card bg-white radius-10 im-flex im-justify-content-start pd-10 im-align-items-center"
                @tap="preview(item)"
              >
                <view class="file-icon cuIcon-text f-36"></view>
                <view class="im-flex im-columns ml-10">
                  <view class="text-overflow file-name">{{ item.fileName }}</view>
                  <view class="text-gray file-size f-12">{{ fileSize(item.fileSize) }}</view>
                </view>
              </view>
            </view>

            <!-- 音视频消息 -->
            <view
              v-else-if="item.type == 'webrtc'"
              @tap="calling(item.extends.type)"
              class="im-voice-msg im-flex im-rows im-nowrap im-align-items-center radius-20"
              :class="[item.fromUser.id == user.user_id ? 'im-rows-reverse' : '']"
            >
              <text
                class="f-16"
                :class="[
                  item.extends.type == 1 ? 'cuIcon-record' : 'cuIcon-dianhua',
                  item.fromUser.id == user.user_id ? 'rotate180' : '',
                ]"
              ></text>
              <text class="im-voice-msg-text">{{ item.content }}</text>
            </view>

            <!-- 其他消息 -->
            <imItem v-else :item="item" :index="index" :isSelf="true"></imItem>
          </view>
          <view class="time" v-if="itme?.time">{{ itme.time || "2020-2-23 14:12" }}</view>
        </view>
      </view>
    </view>
    <view class="empty" v-if="empty">暂无记录</view>
  </Top-Page>
</template>

<script>
import NavBar from "@/components/NavBar/NavBar.vue";
import imItem from "@/components/message/im-item.vue";
import { useloginStore } from "@/store/login";
import pinia from "@/store/index";
const userStore = useloginStore(pinia);
export default {
  data() {
    return {
      user: userStore.userInfo,
      page: 0,
      limit: 12,
      loading: false,
      finished: false,
      empty: false,
      list: [],
      playIndex: -1,
      modelName: "",
      curMsg: "",
      query: {},
    };
  },
  components: { NavBar, imItem },
  onLoad(options) {
    Object.assign(this.query, options);

    this.firstApi();
    // this.getMessageList();
  },
  onReachBottom() {
    if (this.finished) return;
    this.firstApi();
    // this.getMessageList();
  },
  onUnload() {
    this.innerAudioContext.stop();
    this.innerAudioContext.destroy();
  },
  onHide() {
    this.innerAudioContext.stop();
    this.innerAudioContext.destroy();
  },
  methods: {
    // 文件预览
    preview(item) {
      let audioExt = ["mp3", "wav", "acc"];
      let extension = item.content.split(".").pop().toLowerCase();
      if (audioExt.includes(extension)) {
        this.curMsg = item;
        this.modelName = "musicPlay";
        return;
      }
      // #ifdef APP-PLUS || MP-WEIXIN
      let exts = ["doc", "xls", "ppt", "pdf", "docx", "xlsx", "pptx"];
      if (exts.includes(extension)) {
        uni.showLoading({ title: "文件加载中" });
        uni.downloadFile({
          url: item.content,
          success: function (res) {
            uni.hideLoading();
            var filePath = res.tempFilePath;
            uni.openDocument({
              filePath: filePath,
              showMenu: true,
              success: function (res) {
                console.log("打开文档成功");
              },
            });
          },
          fail() {
            uni.hideLoading();
          },
        });
      } else {
        uni.showToast({
          title: "该文件不支持预览！",
          icon: "none",
        });
      }
      // #endif

      // #ifdef H5
      const tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = item.download;
      tempLink.setAttribute("download", item.fileName);
      tempLink.setAttribute("target", "_blank");
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      // #endif
    },
    fileSize(size) {
      return this.$util.getFileSize(size);
    },
    // 播放语音
    playVoice: function (e) {
      var voicelUrl = e.currentTarget.dataset.voice;
      var index = e.currentTarget.dataset.index;
      if (this.playIndex == -1) {
        return this.playNow(voicelUrl, index);
      }
      if (this.playIndex == index) {
        innerAudioContext.stop();
        this.playIndex = -1;
      } else {
        innerAudioContext.stop();
        this.playIndex = -1;
        this.playNow(voicelUrl, index);
      }
    },
    // 语音播放基础函数
    playNow: function (voicelUrl, index) {
      this.playIndex = index;
      innerAudioContext.autoplay = true;
      innerAudioContext.src = voicelUrl;
      innerAudioContext.play();
      return true;
    },
    firstApi() {
      // if (!this.user.work_experience)
      this.postCollectMessageList();
      // if (this.user.work_experience) {
      //   uni.showToast({
      //     title: '输入密码'
      //   });
      // } else {
      //   this.postCollectMessageList();
      // }
    },
    postCollectMessageList() {
      this.$api.msgApi
        .collectMessageList({
          page: ++this.page,
          limit: this.limit,
          toContactId: this.query.id,
          is_group: this.query.is_group,
          channel: this.query.channel ?? 0,
        })
        .then((res) => {
          uni.hideToast();

          // let data = res.data.slice().reverse();
          // let data = res.data.slice().reverse();
          let data = res.data;

          if (res.code != 0) {
            this.empty = true;
          }

          if (res.data.length == 0 && this.page == 1) {
            this.empty = true;
          }

          // 如果返回的数据小于每页的数量
          if (res.data.length < this.limit) {
            this.finished = true;
          }

          if (data.length) {
            this.list.push(...data);
            // data.forEach((it) => {
            //   this.list.unshift(it);
            // });
          }

          this.loading = false;
          // this.$nextTick(() => {
          // });
        })
        .catch((err) => {
          console.log("空");
          this.empty = true;
        });
    },
    onClickLeft() {
      uni.navigateBack({
        delta: 1,
      });
    },
    getMessageList() {
      if (this.finished || this.loading) return;
      this.loading = true;

      this.$api.msgApi
        .getMessageList({
          is_group: this.query.is_group,
          toContactId: this.query.id,
          page: ++this.page,
          limit: this.limit,
        })
        .then((res) => {
          // let data = res.data.slice().reverse();
          let data = res.data;

          // 如果返回的数据小于每页的数量
          if (res.data.length < this.limit) {
            this.finished = true;
          }

          if (data.length) {
            this.list.push(...data);
          }

          this.loading = false;
          // this.$nextTick(() => {
          // });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.collect-box {
  position: relative;
  width: 750rpx;
  min-height: 100vh;
  padding-top: calc(96rpx * var(--amplified_base));
  padding-bottom: 60rpx;

  .empty {
    text-align: center;
    margin-top: 50%;
  }

  .list {
    width: 100%;
    padding: 12rpx;
    display: flex;
    flex-direction: column;
    align-items: flex-start;

    .list-unit {
      width: 100%;
      margin-top: 20rpx;
      display: flex;
      align-items: flex-start;

      .avatar-img {
        flex-shrink: 0;
        width: calc(var(--amplified_base) * 70rpx);
        height: calc(var(--amplified_base) * 70rpx);
        border-radius: 50%;
      }

      .message-wrap {
        position: relative;
        max-width: 80%;
        flex: 1;
        margin-left: 16rpx;
        padding: 16rpx;
        border-radius: 20rpx;
        background-color: #fff;

        .msg-name {
          font-weight: bold;
        }

        .msg-content {
          padding-right: 2em;
          margin-top: 8rpx;
        }

        .time {
          position: relative;
          text-align: right;
          color: #ccc;
        }
      }
    }
  }
}
</style>
